//
//  PWSCalendarView.m
//  PWSCalendar
//
//  Created by Sylar on 3/14/14.
//  Copyright (c) 2014 PWS. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////
#import "PWSCalendarView.h"
#import "PWSCalendarViewCell.h"
#import "Setting.h"
//////////////////////////////////////////////////////////////////////////////
const float PWSCalendarHeadViewHeight = 80;
extern NSString* PWSCalendarViewCellId;
const int   PWSCalendarViewNumber = 1000;
//////////////////////////////////////////////////////////////////////////////
@interface PWSCalendarView()
<PWSCalendarDelegate,
UICollectionViewDataSource,
UICollectionViewDelegate,UIScrollViewDelegate>
{
    // data
    NSDate*            yx_date;
    NSDate*            m_current_date;
    int                m_current_page; //当前页数
    
    // head view
    UIView*            m_view_head;         // height = 80
    UILabel*           m_label_time;        // height = 30
    UIView*            m_view_weekdays;     // height = 20
    
  //  UICollectionView*  m_view_calendar;
}
@end
//////////////////////////////////////////////////////////////////////////////
@implementation PWSCalendarView
@synthesize m_view_calendar;
- (id) initWithFrame:(CGRect)frame
{
    id rt = [self initWithFrame:frame CalendarType:en_calendar_type_month];
    return rt;
}

- (id) initWithFrame:(CGRect)frame CalendarType:(enCalendarViewType)pType
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.type = pType;
        m_current_date = [NSDate date];
        [self SetInitialValue];
    }
    return self;
}

- (void) SetInitialValue
{
    [self SetHeadView];
    [self SetCollectionView];
}

- (void) SetHeadView
{
    float width = self.frame.size.width;
    float origin_x = 0;
    
    m_view_head = [[UIView alloc] init];
    [m_view_head setFrame:CGRectMake(0, 0, width, 60)];
    m_view_head.backgroundColor = [UIColor whiteColor];
    [self addSubview:m_view_head];
    
    // label time
    m_label_time = [[UILabel alloc] init];
    [m_label_time setFrame:CGRectMake(0, origin_x, width, 30)];
    [m_label_time setText:@"2014-2-29"];
    [m_label_time setTextAlignment:NSTextAlignmentCenter];
    [m_view_head addSubview:m_label_time];
    
    // weekdays
    origin_x += 30;
    NSArray* weekdays = [NSArray arrayWithObjects:@"日", @"一", @"二", @"三", @"四", @"五", @"六", nil];
    float day_width = width/7;
    for (int i=0; i<7; i++)
    {
        UILabel* each_day = [[UILabel alloc] init];
        each_day.font = [UIFont systemFontOfSize:15];
        [each_day setText:[weekdays objectAtIndex:i]];
        [each_day setTextAlignment:NSTextAlignmentCenter];
        CGRect each_day_frame = CGRectMake(i*day_width, origin_x, day_width, 30);
        [each_day setFrame:each_day_frame];
        [m_view_head addSubview:each_day];
    }
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 30, width, 1)];
    line.backgroundColor = [UIColor blackColor];
    line.alpha = 0.1;
    [m_view_head addSubview:line];
}

- (void) SetLabelDate:(NSDate*)_date
{
    NSDateFormatter* ff = [[NSDateFormatter alloc] init];
    [ff setDateFormat:@"yyyy 年 MM 月"];
    NSString* date = [ff stringFromDate:_date];
    [m_label_time setText:date];
}

- (void) SetCollectionView
{
    float width = self.frame.size.width;
    float height = self.frame.size.height;
    _layout = [[UICollectionViewFlowLayout alloc] init];
    [_layout setMinimumLineSpacing:0];
    [_layout setMinimumInteritemSpacing:0];
    [_layout setItemSize:CGSizeMake(width, height-60)];
    [_layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //UICollectionView中的一个cell就是一个月
    m_view_calendar = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 60, width, height-60) collectionViewLayout:_layout];
    [m_view_calendar setShowsHorizontalScrollIndicator:NO];
    [m_view_calendar setDelegate:self];
    [m_view_calendar setDataSource:self];
    [m_view_calendar setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:m_view_calendar];
    m_view_calendar.pagingEnabled = YES;
    
    [m_view_calendar registerClass:[PWSCalendarViewCell class] forCellWithReuseIdentifier:PWSCalendarViewCellId.copy];
    //总共1000个cell,默认显示中间的cell
    m_current_page = PWSCalendarViewNumber/2;
    NSIndexPath* mid_index = [NSIndexPath indexPathForRow:m_current_page inSection:0];
    [m_view_calendar scrollToItemAtIndexPath:mid_index atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    //顶部显示当前年月
    [self SetLabelDate:[NSDate date]];
}

//改变行数
- (void)chengeTheNumberOfRows:(NSInteger)TheNumberOfRows{
    
    if ([self.delegate respondsToSelector:@selector(chengeTheNumberOfRows:)]) {
        [self.delegate chengeTheNumberOfRows:TheNumberOfRows];
    }
    
}

// collection view delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return PWSCalendarViewNumber;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    //m_current_date 在init中获得当前时间,并且通过代理在滑动的时候不断地改变他的值
    NSDate* cell_date = m_current_date;
    //默认m_current_page 为500
    if (indexPath.row != m_current_page)
    {
        if (self.type == en_calendar_type_month)
        {   //获取下一页时间
            if (indexPath.row > m_current_page)
            {
                //m_current_date后移一个月的时间点时间
                cell_date = [PWSHelper GetNextMonth:m_current_date];
            }
            else
            {
                //m_current_date前移一个月的时间点时间
                cell_date = [PWSHelper GetPreviousMonth:m_current_date];
            }
        }
        else if (self.type == en_calendar_type_week)
        {   //获取上一页时间
            if (indexPath.row > m_current_page)
            {
                cell_date = [PWSHelper GetNextWeek:m_current_date];
            }
            else
            {
                cell_date = [PWSHelper GetPreviousWeek:m_current_date];
            }
        }
    }
    PWSCalendarViewCell* cell = [m_view_calendar dequeueReusableCellWithReuseIdentifier:PWSCalendarViewCellId.copy forIndexPath:indexPath];
    [cell setDelegate:self];
    yx_date = cell_date;
    NSInteger hang = [self getRows:cell_date];
    if ([self.delegate respondsToSelector:@selector(chengeTheNumberOfRows:)]) {
        if (self.type == en_calendar_type_month) {
            [self.delegate chengeTheNumberOfRows:hang];
        } else {
           [self.delegate chengeTheNumberOfRows:1];
        }
    
    }
    
    if (self.isHideBottom == true) {
        if (self.type == en_calendar_type_month) {
            
            // cell.m_collection_view.frame = CGRectMake(0, 0, Width, 42 * hang);
            //月份
            [cell SetWithDate:cell_date ShowType:self.type];
            
        } else if (self.type == en_calendar_type_week) {
            // cell.m_collection_view.frame = CGRectMake(0, 0, Width, 42);
            //月份
            [cell SetWithDate:cell_date ShowType:self.type];
        }
    }else{
//        [NetWorkRequest getNetRequestData:Plan_InMonth parmeters:@{@"Month":[[HelpObject manager] getCurentTime:@"yyyy/MM/dd" dateN:cell_date]} response:^(NSDictionary *response) {
//            
//            cell.dataArray = response[@"Content"];
//            
//            if (self.type == en_calendar_type_month) {
//                
//                // cell.m_collection_view.frame = CGRectMake(0, 0, Width, 42 * hang);
//                //月份
//                [cell SetWithDate:cell_date ShowType:self.type];
//                
//            } else if (self.type == en_calendar_type_week) {
//                // cell.m_collection_view.frame = CGRectMake(0, 0, Width, 42);
//                //月份
//                [cell SetWithDate:cell_date ShowType:self.type];
//            }
//            
//        } netError:^(NSError *error) {
//            
//        }];
    }
    cell.selectDate = _selectDate;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    float cell_width = collectionView.frame.size.width;
    int pos_x = collectionView.contentOffset.x;
    //计算当前页数
    int index = pos_x/cell_width;
    //不断改变m_current_date的值从而不断改变上一页和下一页的月份
    if (m_current_page != index)
    {
        if (self.type == en_calendar_type_month)
        {
            if (m_current_page > index)
            {
                m_current_date = [PWSHelper GetPreviousMonth:m_current_date];
            }
            else if (m_current_page < index)
            {
                m_current_date = [PWSHelper GetNextMonth:m_current_date];
            }
            m_current_page = index;
        }
        else if (self.type == en_calendar_type_week)
        {
            if (m_current_page > index)
            {
                m_current_date = [PWSHelper GetPreviousWeek:m_current_date];
            }
            else if (m_current_page < index)
            {
                m_current_date = [PWSHelper GetNextWeek:m_current_date];
            }
            m_current_page = index;
        }
    }
    
    [self SetLabelDate:m_current_date];
}


//选择之后直接就是更改界面形式改为一周的或者一月的
- (void) didSelectedIndex:(NSInteger)_index {
    
    if (_index == 1) {
        
        // week
        self.type = en_calendar_type_week;
        
        NSArray* cells = [m_view_calendar visibleCells];
        
        for (PWSCalendarViewCell* each_cell in cells) {
            
            [each_cell setType:en_calendar_type_week];
            
        }
        
    }
    
    if (_index == 2) {
        
        // month
        self.type = en_calendar_type_month;
        
        NSArray* cells = [m_view_calendar visibleCells];
        
        for (PWSCalendarViewCell* each_cell in cells) {
            
            [each_cell setType:en_calendar_type_month];
            
        }
        
    }
    
    [m_view_calendar reloadData];
}

// calendar delegate
- (void) PWSCalendar:(PWSCalendarView *)_calendar didSelecteDate:(NSDate *)_date
{
    if ([self.delegate respondsToSelector:@selector(PWSCalendar:didSelecteDate:)])
    {
        [self.delegate PWSCalendar:self didSelecteDate:_date];
    }
}

- (NSInteger)getRows:(NSDate *)myDate {
    NSDate *firstday;
    [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&firstday interval:NULL forDate:myDate];
    NSUInteger zhouji =[[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:firstday];
    NSRange daysOfMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:myDate];
    //该月的行数
    NSInteger shenyu = daysOfMonth.length - (8 - zhouji);
    NSInteger hangshu;
    hangshu = shenyu % 7 > 0 ? shenyu/7 + 2 : shenyu/7 + 1;
    return hangshu;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //改变行数
    [self.m_view_calendar reloadData];
}

@end
